<template>
  <view class="bg">
    <image class="bgc" src="/static/image/background.png" mode="aspectFill" />
    <canvas
      class="scene"
      id="scene"
      canvas-id="scene"
      type="2d"
      @tap="touch"
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
    >
      <cover-image class="time-img" src="@/static/image/time.png" />
      <cover-image class="record-img" src="@/static/image/record.png" />
      <cover-view class="time-text">{{ gameTimeStr }}</cover-view>
      <cover-view class="record-text">{{ cord }}</cover-view>

      <!-- <cover-image
        class="hole"
        v-for="(item, index) in data"
        :style="{
          position: 'absolute',
          top: item.top + 'rpx',
          left: item.left + 'rpx',
          width: item.width + 'rpx',
          height: item.height + 'rpx'
        }"
        :key="index"
        src="/static/image/hole.png"
        @tap="holeTap(item)"
      /> -->

      <cover-view class="mask" v-if="[1, 2, 3, 5].includes(state)">
        <template v-if="state === 1">
          <cover-view class="title title1">选择难度</cover-view>
          <cover-image
            class="btn diffculty1"
            src="@/static/image/difficulty1.png"
            @tap="init('simple')"
            mode="aspectFill"
          />
          <cover-view class="btn diffculty1" @tap="init('simple')"> 简单 </cover-view>
          <cover-image
            class="btn diffculty2"
            src="@/static/image/difficulty2.png"
            @tap="init('ordinary')"
            mode="aspectFill"
          />
          <cover-view class="btn diffculty2" @tap="init('ordinary')"> 中等 </cover-view>
          <cover-image
            class="btn diffculty3"
            src="/static/image/difficulty3.png"
            @tap="init('diffculty')"
            mode="aspectFill"
          />
          <cover-view class="btn diffculty3" @tap="init('diffculty')"> 困难 </cover-view>
        </template>
        <template v-else-if="state === 2">
          <cover-image
            class="btn start"
            src="@/static/image/difficulty1.png"
            @tap="start"
            mode="aspectFill"
          />
          <cover-view class="btn start" @tap="start"> 开始游戏 </cover-view>
          <!-- <cover-view class="btn start" @tap="start">开始游戏</cover-view> -->
        </template>
        <template v-else-if="state === 3">
          <cover-view class="countdown-box">
            <cover-image
              v-if="countdown === 1"
              class="countdown"
              :class="{ animation: state === 3 }"
              src="@/static/image/1.png"
            />
            <cover-image
              v-else-if="countdown === 2"
              class="countdown"
              :class="{ animation: state === 3 }"
              src="@/static/image/2.png"
            />
            <cover-image
              v-else-if="countdown === 3"
              class="countdown"
              :class="{ animation: state === 3 }"
              src="/static/image/3.png"
            />
          </cover-view>
        </template>
        <template v-else-if="state === 5">
          <cover-view class="title title2">完成训练</cover-view>
          <cover-view class="record">{{ cord }}</cover-view>
          <cover-view class="unit">分</cover-view>
          <cover-image
            class="btn again"
            src="/static/image/difficulty1.png"
            @tap="goAgain"
            mode="aspectFill"
          />
          <cover-view class="btn again" @tap="goAgain"> 再次训练 </cover-view>
          <cover-image
            class="btn back"
            src="@/static/image/difficulty2.png"
            @tap="goBack"
            mode="aspectFill"
          />
          <cover-view class="btn back" @tap="goBack"> 退出训练 </cover-view>
          <!--          <cover-view class="btn again" @tap="goAgain">再次训练</cover-view>
          <cover-view class="btn back" @tap="goBack">退出训练</cover-view> -->
        </template>
      </cover-view>
    </canvas>
    <!-- <button @tap="draw">开始</button>
    <button @tap="stop">结束</button>
    <view> 得分：{{ cord }} </view>
    <label for="showTimes">
      <view>出现间隔(60为1s)</view>
      <input id="showTimes" v-model="config.showTimes" type="number" placeholder="出现间隔" />
    </label>
    <label for="showTimes">
      <view>持续时间(60为1s)</view>
      <input v-model="config.continue" type="number" placeholder="持续时间" />
    </label> -->
  </view>
</template>

<script>
let t = null
let t4 = null
let hamster, point, hole
let hamster1, hamster2
let star1, star2, star3, star4, star5, star6
import { parseTime } from '@/utils/tools'
import data from './index.json'
export default {
  data() {
    return {
      state: 1, // 1 选择难度 2 准备开始 3 倒计时 4 游戏阶段 5 结束记分
      countdown: 3,
      gameTime: 60000,
      mSceneWidth: 0, // 手机屏幕宽度
      mSceneHeight: 0, // 手机屏幕高度
      maxTime: 60000,
      animation: null,
      data: [],
      showTimes: 0,
      config: {
        showTimes: 120,
        continue: 180
      },
      cord: 0,
      diffculty: '',
      hole_width: 269,
      hole_height: 98,
      hamster_width: 175,
      hamster_height: 245,
      point_width: 197,
      point_height: 203,
      star_width: 144,
      star_height: 85
    }
  },
  // 页面加载时
  onLoad() {
    this.mSceneWidth = uni.getWindowInfo().windowWidth
    this.mSceneHeight = uni.getWindowInfo().windowHeight
  },
  computed: {
    gameTimeStr() {
      const str = (this.gameTime / 1000).toFixed(2).replace(/\./, ':')
      if (str.length < 5) {
        return '0' + str
      } else {
        return str
      }
    }
  },
  // 页面加载完毕后
  onReady() {
    // this.init()
    // this.draw()
    wx.getImageInfo({
      src: '../../static/image/hamster.png',
      success: (res) => {
        console.log(res)
      }
    })
    wx.getImageInfo({
      src: '../../static/image/point.png',
      success: (res) => {
        console.log(res)
      }
    })
  },
  methods: {
    init(diffculty) {
      this.diffculty = diffculty

      this.data = data[this.diffculty]

      const query = uni.createSelectorQuery()
      query
        .select('#scene')
        .fields({ node: true, size: true })
        .exec(async (res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')

          canvas.width = res[0].width
          canvas.height = res[0].height

          ctx.clearRect(0, 0, this.mSceneWidth, this.mSceneHeight)

          this.imgLoad('/static/image/hamster.png', canvas).then((image) => {
            hamster = image
          })
          this.imgLoad('/static/image/hamster1.png', canvas).then((image) => {
            hamster1 = image
          })
          this.imgLoad('/static/image/hamster2.png', canvas).then((image) => {
            hamster2 = image
          })
          this.imgLoad('/static/image/star1.png', canvas).then((image) => {
            star1 = image
          })
          this.imgLoad('/static/image/star2.png', canvas).then((image) => {
            star2 = image
          })
          this.imgLoad('/static/image/star3.png', canvas).then((image) => {
            star3 = image
          })
          this.imgLoad('/static/image/star4.png', canvas).then((image) => {
            star4 = image
          })
          this.imgLoad('/static/image/star5.png', canvas).then((image) => {
            star5 = image
          })
          this.imgLoad('/static/image/star6.png', canvas).then((image) => {
            star6 = image
          })
          this.imgLoad('/static/image/point.png', canvas).then((image) => {
            point = image
          })
          this.imgLoad('/static/image/hole.png', canvas).then((image) => {
            hole = image
            this.data.map((v) => {
              ctx.drawImage(
                hole,
                uni.upx2px(v.left),
                uni.upx2px(v.top),
                uni.upx2px(v.width),
                uni.upx2px(v.height)
              )
            })
          })

          // const image = canvas.createImage()
          // image.onload = () => {
          //   hamster = image
          // }
          // image.src = '/static/image/hamster.png'

          // const image2 = canvas.createImage()
          // image2.onload = () => {
          //   point = image2
          // }
          // image2.src = '/static/image/point.png'

          // const image3 = canvas.createImage()
          // image3.onload = () => {
          //   hole = image3

          //   this.data.map((v) => {
          //     ctx.drawImage(
          //       hole,
          //       uni.upx2px(v.left),
          //       uni.upx2px(v.top),
          //       uni.upx2px(v.width),
          //       uni.upx2px(v.height)
          //     )
          //   })
          // }
          // image3.src = '/static/image/hole.png'

          // this.hole = await this.imgLoad('../../static/image/hole.png', canvas)

          // this.data.map((v) => {
          //   ctx.beginPath()
          //   // ctx.drawImage(this.hole, v.left / 2, v.top / 2, v.width / 2, v.height / 2)
          //   ctx.drawImage(this.hole, v.left / 2, v.top / 2, v.width / 2, v.height / 2)
          //   ctx.closePath()
          // })

          this.state = 2
        })
    },
    imgLoad(url, canvas) {
      return new Promise((resolve, reject) => {
        const image = canvas.createImage()
        image.onload = () => {
          // 将图片绘制到 canvas 上
          console.log('图片加载成功')
          resolve(image)
        }
        image.src = url
      })
    },
    playVideo(str) {
      const maps = {
        point: '/static/video/point.mp3',
        empty: '/static/video/empty.mp3'
      }

      let innerAudioContext = uni.createInnerAudioContext()
      innerAudioContext.autoplay = true
      innerAudioContext.src = maps[str]
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })

      innerAudioContext.onEnded(() => {
        console.log('开始播放')
        innerAudioContext.destroy()
        innerAudioContext = null
      })
    },
    start() {
      this.state = 3

      this.gameTime = 60000
      this.cord = 0

      t = setInterval(() => {
        if (this.countdown === 1) {
          this.state = 4

          t4 = setInterval(() => {
            if (this.gameTime - 10 < 0) {
              this.gameTime = 0
              clearInterval(t4)
              t4 = null

              this.stop()

              this.state = 5
            } else {
              this.gameTime = this.gameTime - 10
            }
          }, 10)

          this.draw()
          clearInterval(t)
          t = null
          this.countdown = 3
        } else {
          this.countdown--
        }
      }, 1000)
    },
    stop() {
      const query = wx.createSelectorQuery()
      query
        .select('#scene')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node

          canvas.cancelAnimationFrame(this.animation)

          // const ctx = canvas.getContext('2d')
          // ctx.clearRect(0, 0, this.mSceneWidth, this.mSceneHeight)
        })
      // this.init()
    },
    draw() {
      const query = wx.createSelectorQuery()
      query
        .select('#scene')
        .fields({ node: true, size: true })
        .exec(async (res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')

          ctx.clearRect(0, 0, this.mSceneWidth, this.mSceneHeight)

          for (let i = 0; i < this.data.length; i++) {
            const v = this.data[i]

            ctx.drawImage(
              hole,
              uni.upx2px(v.left),
              uni.upx2px(v.top),
              uni.upx2px(v.width),
              uni.upx2px(v.height)
            )

            if (v.child.show) {
              if (v.child.times >= this.config.continue) {
                if (v.child.type === 'start') {
                  this.playVideo('empty')
                }
                v.child.show = false
                v.child.times = 0
                v.child.type = 'start'
                v.child.showHeight = 0
              } else {
                v.child.times = v.child.times + 1
                if (v.child.type === 'start') {
                  const speed = 10
                  if (v.child.showHeight + speed <= v.child.height) {
                    v.child.showHeight = v.child.showHeight + speed
                  } else {
                    v.child.showHeight = v.child.height
                  }
                  // const image = await this.imgLoad('/static/image/hamster.png', canvas)
                  ctx.drawImage(
                    hamster1,
                    0,
                    0,
                    this.hamster_width,
                    (v.child.showHeight / v.child.height) * this.hamster_height,
                    uni.upx2px((v.left / 2 + (v.width - v.child.width) / 4) * 2),
                    uni.upx2px((v.top / 2 + v.height / 2 - v.child.showHeight / 2) * 2),
                    uni.upx2px(v.child.width),
                    uni.upx2px(v.child.showHeight)
                  )
                } else if (v.child.type === 'point') {
                  if (v.child.point.rotate === v.child.point.rotateEnd) {
                    v.child.times = 0
                    v.child.type = 'star'
                    v.child.showHeight = 0
                    v.child.point.show = false
                    v.child.point.rotate = 2
                    v.child.star.show = true
                  } else if (
                    v.child.point.rotate - v.child.point.rotateSpeed <=
                    v.child.point.rotateEnd
                  ) {
                    v.child.point.rotate = v.child.point.rotateEnd
                  } else {
                    v.child.point.rotate = v.child.point.rotate - v.child.point.rotateSpeed
                  }
                  if (v.child.point.show) {
                    ctx.drawImage(
                      hamster1,
                      0,
                      0,
                      this.hamster_width,
                      this.hamster_height,
                      uni.upx2px((v.left / 2 + (v.width - v.child.width) / 4) * 2),
                      uni.upx2px((v.top / 2 + v.height / 2 - v.child.height / 2) * 2),
                      uni.upx2px(v.child.width),
                      uni.upx2px(v.child.height)
                    )
                    ctx.save()
                    ctx.translate(
                      uni.upx2px(
                        (v.left / 2 +
                          (v.width - v.child.point.width) / 2 +
                          v.child.point.width / 4) *
                          2
                      ),
                      uni.upx2px(
                        (v.top / 2 +
                          v.height / 2 -
                          (v.child.point.height / 4) * 3 +
                          v.child.point.height / 4) *
                          2
                      )
                    )
                    ctx.rotate(v.child.point.rotate * Math.PI)
                    ctx.drawImage(
                      point,
                      -uni.upx2px((v.child.point.width / 5) * 2),
                      -uni.upx2px((v.child.point.height / 4) * 2),
                      uni.upx2px(v.child.point.width),
                      uni.upx2px(v.child.point.height)
                    )
                    ctx.restore()
                    // ctx.translate(0, 0)
                  }
                } else if (v.child.type === 'star') {
                  if (v.child.star.time === v.child.star.timeEnd) {
                    v.child.type = 'end'
                    v.child.star.show = false
                    v.child.star.time = 0
                  } else {
                    v.child.star.time = v.child.star.time + 1
                  }
                  if (v.child.star.show) {
                    ctx.drawImage(
                      hamster2,
                      0,
                      0,
                      this.hamster_width,
                      this.hamster_height,
                      uni.upx2px((v.left / 2 + (v.width - v.child.width) / 4) * 2),
                      uni.upx2px((v.top / 2 + v.height / 2 - v.child.height / 2) * 2),
                      uni.upx2px(v.child.width),
                      uni.upx2px(v.child.height)
                    )

                    const stars = {
                      star1: star1,
                      star2: star2,
                      star3: star3,
                      star4: star4,
                      star5: star5,
                      star6: star6
                    }
                    ctx.drawImage(
                      stars[`star${Math.ceil(((v.child.star.time % 30) + 1) / 5)}`],
                      0,
                      0,
                      this.star_width,
                      this.star_height,
                      uni.upx2px(
                        (v.left / 2 + (v.width - v.child.width) / 4) * 2 + v.child.star.offest_left
                      ),
                      uni.upx2px(
                        (v.top / 2 + v.height / 2 - v.child.height / 2) * 2 +
                          v.child.star.offest_top
                      ),
                      uni.upx2px(v.child.star.width),
                      uni.upx2px(v.child.star.height)
                    )
                  }
                }
              }
            }
          }

          if (!this.showTimes) {
            const f = this.data.filter((v) => !v.child.show)

            if (f.length) {
              const random = Math.floor(Math.random() * f.length)

              f[random].child.show = true
              f[random].child.times++

              this.showTimes = 1
            }
          } else if (this.showTimes >= this.config.showTimes) {
            this.showTimes = 0
          } else {
            this.showTimes++
          }

          if (this.state === 4) {
            this.animation = canvas.requestAnimationFrame(this.draw)
          }
        })

      // const ctx = uni.createCanvasContext('scene')

      // ctx.clearRect(0, 0, this.mSceneWidth, this.mSceneHeight)

      // this.data.map((v) => {
      //   // ctx.beginPath()
      //   ctx.arc(uni.upx2px(v.left + v.r), uni.upx2px(v.top + v.r), uni.upx2px(v.r), 0, Math.PI * 2)
      //   ctx.setFillStyle(v.color)
      //   ctx.fill()

      //   if (v.child.show) {
      //     if (v.child.times >= this.config.continue) {
      //       v.child.show = false
      //       v.child.times = 0
      //       v.child.type = 'start'
      //     } else {
      //       v.child.times = v.child.times + 1
      //       if (v.child.type !== 'end') {
      //         ctx.beginPath()
      //         ctx.arc(
      //           uni.upx2px(v.left + v.r),
      //           uni.upx2px(v.top + v.r),
      //           uni.upx2px(v.child.r),
      //           0,
      //           Math.PI * 2
      //         )
      //         ctx.setFillStyle(v.child.color)
      //         ctx.fill()
      //       }
      //     }
      //   }
      // })

      // if (!this.showTimes) {
      //   const f = this.data.filter((v) => !v.child.show)

      //   if (f.length) {
      //     const random = Math.floor(Math.random() * f.length)

      //     f[random].child.show = true
      //     f[random].child.times++

      //     this.showTimes = 1
      //   }
      // } else if (this.showTimes >= this.config.showTimes) {
      //   this.showTimes = 0
      // } else {
      //   this.showTimes++
      // }

      // ctx.draw()

      // this.animation = requestAnimationFrame(this.draw)
    },
    holeTap(item) {
      if (item.child.type !== 'end' && item.child.type !== 'point') {
        item.child.type = 'point'
        item.child.point.show = true

        this.cord++
        console.log('打中了')
      }
    },
    touch(e) {
      console.log(e.detail.x, e.detail.y - e.currentTarget.offsetTop)
      const c = {
        x: e.detail.x,
        y: e.detail.y - e.currentTarget.offsetTop
      }

      this.data.map((v) => {
        if (v.child.show) {
          const rect = {
            top: uni.upx2px(v.top / 2 + v.height / 2 - v.child.height / 2) * 2,
            left: uni.upx2px(v.left / 2 + (v.width - v.child.width) / 4) * 2,
            width: uni.upx2px(v.child.width / 2) * 2,
            height: uni.upx2px(v.child.height / 2) * 2
          }

          console.log(c, rect)

          if (
            c.x >= rect.left &&
            c.x <= rect.left + rect.width &&
            c.y >= rect.top &&
            c.y <= rect.top + rect.height
          ) {
            if (v.child.type !== 'end' && v.child.type !== 'point' && v.child.type !== 'star') {
              v.child.type = 'point'
              v.child.point.show = true

              this.cord++

              this.playVideo('point')
              console.log('打中了')
            }
          }
        }
      })
    },
    goAgain() {
      const query = wx.createSelectorQuery()
      query
        .select('#scene')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          ctx.clearRect(0, 0, this.mSceneWidth, this.mSceneHeight)

          this.data = data[this.diffculty]

          this.data.map((v) => {
            ctx.drawImage(
              hole,
              uni.upx2px(v.left),
              uni.upx2px(v.top),
              uni.upx2px(v.width),
              uni.upx2px(v.height)
            )
          })
        })
      this.start()
    },
    goBack() {
      console.log('退出游戏')
      uni.reLaunch({
        url: '/pages/index/index'
      })
    },
    // 触摸开始
    touchStart(e) {},
    // 触摸移动中
    touchMove(e) {},
    // 触摸结束
    touchEnd(e) {}
  }
}
</script>

<style lang="scss" scoped>
.scene {
  width: 100vw;
  height: 100vh;
}

.bg {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.bgc {
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
  width: 100vw;
  height: 100vh;
}

.time-img {
  position: absolute;
  top: 20rpx;
  left: 36rpx;
  width: 253rpx;
  height: 95rpx;
}

.time-text {
  position: absolute;
  top: 44rpx;
  left: 158rpx;
  width: 100rpx;
  font-family: 'FZZongYi-M05S';
  font-size: 36rpx;
  font-weight: 400;
  line-height: 42rpx;
  color: #fff;
}

.record-img {
  position: absolute;
  top: 20rpx;
  right: 40rpx;
  width: 263rpx;
  height: 95rpx;
}

.record-text {
  position: absolute;
  top: 46rpx;
  right: 118rpx;
  font-family: 'FZZongYi-M05S';
  font-size: 36rpx;
  font-weight: 400;
  line-height: 42rpx;
  color: #fff;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgb(0 0 0 / 50%);

  .title {
    position: absolute;
    left: 50%;
    font-family: 'PingFang SC';
    font-size: 48rpx;
    font-weight: 500;
    line-height: 56rpx;
    color: #fff;
    transform: translate(-50%, 0);
  }

  .title1 {
    top: 282rpx;
  }

  .title2 {
    top: 176rpx;
  }

  .btn {
    position: absolute;
    left: 50%;
    width: 542rpx;
    height: 140rpx;
    font-family: 'PingFang SC';
    font-size: 48rpx;
    font-weight: 500;
    line-height: 140rpx;
    color: #fff;
    text-align: center;
    transform: translate(-50%, 0);
  }

  .diffculty1 {
    top: 478rpx;
  }

  .diffculty2 {
    top: 678rpx;
  }

  .diffculty3 {
    top: 882rpx;
  }

  .start {
    top: 656rpx;
  }

  .record {
    position: absolute;
    top: 246rpx;
    right: 254rpx;
    margin-right: 20rpx;
    font-family: 'PingFang SC';
    font-size: 320rpx;
    font-weight: 500;
    line-height: 448rpx;
    color: #fff;
    text-shadow: 0 12px 0 rgb(0 0 0 / 60%);
    -webkit-text-stroke: 4rpx #a1c8a7;
  }

  .unit {
    position: absolute;
    top: 490rpx;
    right: 152rpx;
    font-family: 'PingFang SC';
    font-size: 88rpx;
    font-weight: 500;
    line-height: 124rpx;
    color: #fff;
    text-shadow: 0 12px 0 rgb(0 0 0 / 60%);
    -webkit-text-stroke: 4rpx #a1c8a7;
  }

  .again {
    top: 838rpx;
  }

  .back {
    top: 1024rpx;
  }
}

@keyframes reduce {
  from {
    transform: scale(1);
  }

  to {
    transform: scale(0.3);
  }
}

.countdown-box {
  position: absolute;
  top: 382rpx;
  left: 50%;
  width: 250rpx;
  height: 512rpx;
  transform: translate(-50%, 0);
}

.countdown {
  width: 250rpx;
  height: 512rpx;
  transform: scale(1);
}

.animation {
  animation: reduce 1s linear 0s 1;
}
</style>
